package cn.cloudtogo.server;

import cn.cloudtogo.common.GendbException;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import cn.cloudtogo.common.model.ExternalDatasourceModel;
import cn.cloudtogo.common.types.RequestHeaderObject;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import static cn.cloudtogo.common.GendbGlobalConstant.DATASOURCE_KEY;

public class RequestHeaderObjectArgumentResolver implements HandlerMethodArgumentResolver {

    private final ExternalDatasourceDao datasourceDao;

    public RequestHeaderObjectArgumentResolver(ExternalDatasourceDao datasourceDao) {
        this.datasourceDao = datasourceDao;
    }

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return RequestHeaderObject.class.equals(parameter.getParameterType());
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String uuid = webRequest.getHeader(DATASOURCE_KEY);

        if (!StringUtils.hasText(uuid)) {
            throw new GendbException("request header parameter [" + DATASOURCE_KEY + "] is missing");
        }
        ExternalDatasourceModel model = datasourceDao.query(uuid);
        if (null == model) {
            throw new GendbException("request header parameter [" + DATASOURCE_KEY + "] invalid");
        }
        return RequestHeaderObject.ofModel(model);


    }
}
